package com.tmxk.api.days01.set;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class SetDemo {
    public static void main(String[] args) {
        Dog dog1 = new Dog("小花",2);
        Dog dog2 = new Dog("花花",3);
        Dog dog3 = new Dog("小黑",1);
        Dog dog4 = new Dog("小白",5);
        Dog dog5 = new Dog("汪汪",6);

        //创建Set集合对象,父类对象引用指向子类实例(多态体现)
        Set<Dog> dogSet = new HashSet<>();
        dogSet.add(dog1);
        dogSet.add(dog1);
        dogSet.add(dog2);
        dogSet.add(dog3);
        dogSet.add(dog4);
        dogSet.add(dog5);
        //获取HashSet集合元素的大小
        System.out.println("dogSet的长度:" + dogSet.size());
        //获取 set集合元素
        System.out.println("使用for循环遍历");
        for (Dog dog : dogSet){
            System.out.print(dog.getName() + "\t" + dog.getAge());
        }

        System.out.print("使用lambda表达式遍历");
        dogSet.forEach(dog -> {
            System.out.println(dog.getName() + "\t" + dog.getAge());
        });

        System.out.println("使用迭代器集合元素遍历  方式三");
        Iterator<Dog> it = dogSet.iterator();
        //it.hasNext():获取下一个迭代元素是否存在
        while(it.hasNext()){
            //it.next():遍历下一个集合元素
            Dog dog = it.next();
            System.out.println(dog.getName() + "\t" + dog.getAge());
        }



        //TreeSet
        TreeSet<Dog> dogTreeSet = new TreeSet<>();
        dogTreeSet.add(dog1);
        dogTreeSet.add(dog2);
        dogTreeSet.add(dog3);
        //dogTreeSet.add(dog4);
        //dogTreeSet.add(dog5);
    }
}
